#!/usr/bin/perl

use SGraph;
use SGraph::Dot;

unless (-e $ARGV[0]){
   print "provide network information in graphviz format\n";
   die;
}

our $g=new SGraph;
$g->dot($ARGV[0]);
my $haspos=1;
for my $i (@{$g->nodes}){ # check whether layout information is complete
   $haspos=0 unless $g->has_attribute($i,"pos") && $g->has_attribute($i,"width") && $g->has_attribute($i,"height");
}

our @lines=<STDIN>;
our $l;
while (!($lines[0]=~/begin report/)){shift(@lines)};
#while ($l=shift(@lines) && (!($l=~/begin report/))){}
shift(@lines);
$l=shift(@lines);
our @ids=split(/\s+/,$l);
shift(@ids); # time
print @ids;
our $cc=0;
for my $l (@lines){
   $l=~s/\n//;
   my @cols=split(/\s+/,$l);
   shift(@cols); # time
   for (my $i=0;$i<scalar(@cols);$i++){
      my $id=$ids[$i];
      unless ($g->has_node($id)){
         print "ups, node '$id' not in graphviz file\n";
         next;
      }
      $g->set_attribute($id,'style','filled');
      if ($cols[$i]>0){
         $g->set_attribute($id,'fillcolor','green');
      } elsif ($cols[$i]<0){
         $g->set_attribute($id,'fillcolor','red');
      } else {
         $g->set_attribute($id,'fillcolor','white');
      }
   }
   my $fh;
   my $frame = sprintf("%05d", $cc++);
   if ($haspos){
      open($fh,"| neato -n -Gsize=\"12,9\" -Gsplines=true -Gdpi=100 -Tpng -o /tmp/libScopes_ani_".$$."_$frame.png");
   } else {
      open($fh,"| dot -Gsize=\"12,9\" -Gsplines=true -Gdpi=100 -Tpng -o /tmp/libScopes_ani_".$$."_$frame.png");
   }
   print $fh $g->dot;
   close $fh;
}
#system("mencoder \"mf:///tmp/libScopes_ani_".$$."_*jpg\" -mf fps=2 -o libScopes_ani.avi -ovc lavc -lavcopts vcodec=mpeg4");
#system("MAGICK_TMPDIR=/local/home/handorf/tmp/ convert -limit memory 64 -limit map 128 -delay 50 -quality 92 -size 1200x900 /tmp/libScopes_ani_".$$."_*.png -loop 1 libScopes_ani.mp4");
system("convert -limit memory 64 -limit map 128 -delay 50 -quality 92 -size 1200x900 /tmp/libScopes_ani_".$$."_*.png -loop 1 libScopes_ani".$$.".mp4");
system("rm /tmp/libScopes_ani_".$$."_*");